//
//  SZMineMainController.m
//  KaiJing
//
//  Created by lanou on 16/1/11.
//  Copyright © 2016年 HuangZuCui. All rights reserved.
//

#import "SZMineMainController.h"
#import "SZMineMainHeaderVew.h"
#import "SZLoginViewController.h"
#import "SZCountryCityController.h"
#import "SZLoginTool.h"
#import "PKRequestManager.h"
#import <SDWebImageManager.h>
#import "DXAlertView.h"
#import "SZBaseNavController.h"

// 按钮高度
#define kButtonHeight 140
// 退出登陆网址
#define kLoginoutURL @"http://morguo.com/member.php?mod=logging&action=logout&androidflag=1&appfrom=ios&iosversion=3.13"
@interface SZMineMainController ()
/** cell数据源 */
@property (nonatomic, strong) NSArray *dataSource;
/** 退出按钮 */
@property (nonatomic, strong) UIButton *loginutButton;
@property (nonatomic, strong) SZMineMainHeaderVew *headerView;
@end

@implementation SZMineMainController
- (void)viewWillAppear:(BOOL)animated {
    if (![[SZLoginTool shareLogin] isLogin]) {
        _headerView.nameLabel.text = @"请登录";
    } else {
        _headerView.nameLabel.text = [[SZLoginTool shareLogin] userName];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // 初始化数据源
    _dataSource = @[@"清除缓存", @"我的位置"];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"SZMineMainCell"];
    [self addHeaderFooterTableView];
    
}

// 添加表头表尾
- (void)addHeaderFooterTableView {
    _headerView = [[SZMineMainHeaderVew alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kButtonHeight)];
    self.tableView.tableHeaderView = _headerView;
    
    [_headerView.iconButton addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    
    _loginutButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _loginutButton.frame = CGRectMake(0, 0, kScreenWidth, 40);
    [_loginutButton setTitle:@"退出登陆" forState:UIControlStateNormal];
    [_loginutButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [_loginutButton addTarget:self action:@selector(loginout) forControlEvents:UIControlEventTouchUpInside];
    self.tableView.tableFooterView = _loginutButton;
}

- (void)login {
    SZLoginViewController *loginVC = [[SZLoginViewController alloc] init];
    SZBaseNavController *nav = [[SZBaseNavController alloc] initWithRootViewController:loginVC];
//    __block SZMineMainController *tempSelf = self;
//    loginVC.block = ^ (NSString *userName) {
//        tempSelf.headerView.nameLabel.text = userName;
//    };
    [self presentViewController:nav animated:YES completion:nil];
}

/**
 *  退出登陆
 */
- (void)loginout {
    if (![[SZLoginTool shareLogin] isLogin]) {
        DXAlertView *alert = [[DXAlertView alloc] initWithTitle:@"已经退出" contentText:@"别点了亲..." leftButtonTitle:nil rightButtonTitle:@"完成"];
        [alert show];
        return;
    }
    [PKRequestManager requestWithUrlString:kLoginoutURL parDic:nil method:GET finish:^(NSDictionary *dataDic) {
        SZLog(@"%@",dataDic);
        [[SZLoginTool shareLogin] saveLoginStateWithString:@"0"];
        self.headerView.nameLabel.text = @"请登录";
        DXAlertView *alert = [[DXAlertView alloc] initWithTitle:@"退出成功" contentText:@"已经退出..." leftButtonTitle:nil rightButtonTitle:@"完成"];
        [alert show];
    } error:^(NSError *error) {
        SZLog(@"%@",error);
    }];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SZMineMainCell" forIndexPath:indexPath];
    cell.textLabel.text = _dataSource[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 选中了我的位置
    if (indexPath.row == 1) {
        SZCountryCityController *cityVC = [[SZCountryCityController alloc] init];
        [self.navigationController pushViewController:cityVC animated:YES];
    }
    if (indexPath.row == 0) {
        [self clearCatche];
    }
}

/**
 *  清除图片缓存(删除Caches文件夹)
 */
- (void)clearCatche {
    NSFileManager *manager = [NSFileManager defaultManager];
    NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    SZLog(@"%@",path);
    NSError *error = nil;
    CGFloat size = [self folderSizeAtPath:path];
    [manager removeItemAtPath:path error:&error];
    if (error) SZLog(@"%@",error.localizedFailureReason);
    
    DXAlertView *alert = [[DXAlertView alloc] initWithTitle:@"清除缓存成功" contentText:[NSString stringWithFormat:@"清理了%.0fM垃圾",size]  leftButtonTitle:nil rightButtonTitle:@"完成"];
    [alert show];
}


- (float ) folderSizeAtPath:(NSString*) folderPath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if (![manager fileExistsAtPath:folderPath]) return 0;
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    
    NSString* fileName;
    
    long long folderSize = 0;
    
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
        
    }
    
    return folderSize/(1024.0*1024.0);
    
}


- (long long) fileSizeAtPath:(NSString*) filePath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]){
        
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}
@end
